import { userStore } from "@/stores"
import Toast from "@/wxcomponents/@vant/weapp/toast/toast"
// 拦截重复请求白名单
let whiteList: string[] = []
// 拦截重复请求
const requestSet = new Set()

// 请求拦截器
export const requestInterceptor = (instance) => {
  instance.interceptors.request.use(function (request) {
    console.log(request)
    // 拦截重复请求
    // 添加请求url到set
    if (requestSet.has(request.url) && !whiteList.includes(request.url)) {
      //终止请求
      let err = new Error("重复请求!")
      err["request"] = request
      return Promise.reject(err)
    }
    requestSet.add(request.url)

    //给所有请求添加自定义header
    let jwtToken = userStore.token
    if (jwtToken) {
      // 添加JWT Token
      request.headers["Authorization"] = `Bearer ${jwtToken}`
    }
    uni.showLoading({
      mask: true,
      title: "加载中"
    })
    //可以显式返回request, 也可以不返回，没有返回值时拦截器中默认返回request
    return request
  })
}

// 响应拦截器
export const responseInterceptor = (instance) => {
  instance.interceptors.response.use(
    function (response) {
      uni.hideLoading()
      if (requestSet.has(response.request.url)) {
        requestSet.delete(response.request.url)
      }
      if (response?.data?.code === "200") {
        return Promise.resolve(response.data)
      }
      businessStatus(response)
      return Promise.reject(response.data)
    },
    function (error) {
      uni.hideLoading()
      if (error?.code === 0) {
        Toast({
          type: "fail",
          message: "网络错误，请检查网络",
          forbidClick: true
        })
      }
      if (error?.code === 1) {
        Toast({
          type: "fail",
          message: "请求超时",
          forbidClick: true
        })
      }
      if (error?.code === "ERR_CANCELED") {
        Toast({
          type: "fail",
          message: "请求已取消",
          forbidClick: true
        })
      }
      if (error.response?.status) {
        browserStatus(error.response)
      }
      return Promise.reject(error)
    }
  )
}

// 业务状态处理
const businessStatus = (response: any) => {
  const whiteCodeList = [2007, 2006] // code白名单（不弹窗提示）
  if (whiteCodeList.includes(Number(response.data.code))) return
  // if (response.data.code === "2013") {
  //   notification.error({ message: "提示", description: response.data.msg })
  // }
  Toast({
    type: "fail",
    message: response.data.message || "发生错误！",
    forbidClick: true
  })
}

// 浏览器状态处理
const browserStatus = (response: any) => {
  switch (response.status) {
    // 未登录
    case 401:
      Toast({
        type: "fail",
        message: "用户未登录",
        forbidClick: true
      })
      break

    // 登录过期
    case 403:
      Toast({
        type: "fail",
        message: "登录状态已过期",
        forbidClick: true
      })
      break

    //资源不存在
    case 404:
      Toast({
        type: "fail",
        message: "资源不存在",
        forbidClick: true
      })
      break

    // 服务端错误
    case 500:
      Toast({
        type: "fail",
        message: "服务端错误",
        forbidClick: true
      })
      break

    // 其他status
    default:
      Toast({
        type: "fail",
        message: "网络错误，请刷新后再试",
        forbidClick: true
      })
      break
  }
}
